import { Dispatch, RefObject, SetStateAction, useState } from 'react';

import { SelectProps } from '@/shared/interfaces';
import { useRouter } from 'next/router';
import { useDebounceValue } from 'usehooks-ts';

export const handleMultipleSelect = <T extends ISelectedPool>(
  setValue: Dispatch<SetStateAction<T[]>>,
  condition: boolean,
  newValue: T,
): void => {
  if (condition) {
    setValue((_value) =>
      _value?.filter((item) => (item.id + item.arr).toString() !== (newValue.id + newValue.arr).toString()),
    );
    return;
  }
  setValue((_value) => [newValue, ..._value]);
};
export type ISelectedPool = SelectProps & { arr: 'formats' | 'topics' };
export const useFilters = () => {
  const [isFiltersOpen, setIsFiltersOpen] = useState(false);
  const [selectedPool, setSelectedPool] = useState<ISelectedPool[]>([]);

  const handleClearFilters = () => {
    setSelectedPool([]);
  };
  const handlePoolSelect = (pool: ISelectedPool) => {
    handleMultipleSelect(
      setSelectedPool,
      !!selectedPool?.find((item) => (item.id + item.arr).toString() === (pool.id + pool.arr).toString()),
      pool,
    );
  };

  const handleOpenModal = () => {
    setIsFiltersOpen(() => true);
  };
  const handleCloseModal = () => {
    setIsFiltersOpen(() => false);
  };
  const handleSaveNewFilters = (item: ISelectedPool[]) => {
    setSelectedPool(() => item);
    handleCloseModal();
  };
  return {
    selectedPool,
    handlePoolSelect,
    isFiltersOpen,
    handleClearFilters,
    handleSaveNewFilters,
    handleOpenModal,
    handleCloseModal,
  };
};

export type FilterProps = ReturnType<typeof useFilters>;

export const useSorts = ({ sorts }: { sorts: SelectProps[] }) => {
  const [selectedSort, setSelectedSort] = useState<SelectProps>(sorts[0]);
  const [isSortsOpen, setIsSortsOpen] = useState(false);

  const handleSelectSort = (item: SelectProps) => {
    setSelectedSort(() => item);
    setIsSortsOpen(false);
  };
  const handleOpenSortModal = () => {
    setIsSortsOpen(() => true);
  };
  const handleCloseSortModal = () => {
    setIsSortsOpen(() => false);
  };

  return { isSortsOpen, selectedSort, handleSelectSort, handleOpenSortModal, handleCloseSortModal };
};

const FOCUS_DELAY = 200;

export const useIsInputInFocus = ({ inputRef }: { inputRef: RefObject<HTMLInputElement> }) => {
  const [isInputInFocus, setIsInputInFocus] = useState(false);
  const router = useRouter();
  const [search] = useDebounceValue((router.query.search as string) || '', 300);
  const [isInputMode, setIsIsInputMode] = useState(!!search);
  let timeoutFocus: NodeJS.Timeout;
  let timeoutBlur: NodeJS.Timeout;
  const onFocus = async () => {
    if (!inputRef?.current) return;
    inputRef.current.focus();
    clearTimeout(timeoutBlur);
    timeoutFocus = setTimeout(() => {
      setIsInputInFocus(true);
      setIsIsInputMode(() => true);
      window.scrollTo(0, 0);
    }, FOCUS_DELAY);
  };

  const onBlur = () => {
    if (!inputRef?.current) return;
    inputRef.current.blur();
  };

  const handleCancelSearch = () => {
    clearTimeout(timeoutFocus);
    timeoutBlur = setTimeout(() => {
      setIsInputInFocus(false);
      window.scrollTo(0, 0);
      setIsIsInputMode(() => false);
    }, FOCUS_DELAY);
  };
  return { isInputInFocus, onBlur, onFocus, isInputMode, handleCancelSearch };
};

export type InputFocusProps = ReturnType<typeof useIsInputInFocus>;
